<?php

namespace app\controllers;

use Yii;
use app\models\Image;
use app\models\zipfile;

class ImageController extends MainController {
   
    public function actionUpload2() {
        if (Yii::$app->request->post('uploadpic') == '上传') {
            $upload_path = './uploads/' . date('Ymd') . '/';
            $success_file_arr = [];
            $error_file_arr = [];
            $count = 0;
            $success_count = 0;
            $error_count = 0;
            if (!file_exists($upload_path))
                mkdir($upload_path, 755);
            $tp = ["image/jpeg", "image/png"];
             if (!in_array($_FILES["file"]["type"], $tp) && $_FILES["file"]['error'] != 0) {
                 die('文件错误,上传失败!');
             }else{
                $tmp_name = $_FILES["file"]["tmp_name"];
                $a = explode(".", $_FILES["file"]["name"]);
                $prename = $a[0];
                $name = md5(time() . mt_rand(10000, 99999));
                $ext = $a[1];
                $uploadfile = $upload_path . $name . '.' . $ext;     // 文件的路径
                if (move_uploaded_file($tmp_name, $uploadfile)) {
                        $imageModel = new Image();
                        $data = [
                            'imgurl' => '' . date('Ymd') . '/'.$name . '.' . $ext,
                            'original_image' => $prename,
                            'image_ext'=>$ext
                        ];
                        $imageModel->insertPostImage($data);
                        $response = [
                           'IsSuccess'=>true,
                            'Url'=>$uploadfile,
                            'Message'=>'上传成功'
                        ];
                       echo json_encode($response);die;
                } else {
                       die('图片上传失败!');
                 }
             }
            
//            foreach ($_FILES['uploads']['error'] as $key => $error) {
//                if (!in_array($_FILES["uploads"]["type"][$key], $tp) && $error != 0) {
//                    $error_count++;
//                    $error_file_arr[$error_count] = $_FILES["uploads"]["name"][$key];
//                } else {
//                    $tmp_name = $_FILES["uploads"]["tmp_name"][$key];
//                    $a = explode(".", $_FILES["uploads"]["name"][$key]);
//                    $prename = $a[0];
//                    $name = md5(time() . mt_rand(10000, 99999));
//                    $ext = $a[1];
//                    $uploadfile = $upload_path . $name . '.' . $ext;     // 文件的路径
//                    if (move_uploaded_file($tmp_name, $uploadfile)) {
//                        $success_count++;
//                        $success_file_arr[$success_count] = $uploadfile;
//                        $imageModel = new Image();
//                        $data = [
//                            'imgurl' => '' . date('Ymd') . '/'.$name . '.' . $ext,
//                            'original_image' => $prename,
//                            'image_ext'=>$ext
//                        ];
//                        $imageModel->insertPostImage($data);
//                    } else {
//                        $error_count++;
//                        $error_file_arr[$error_count] = $_FILES["uploads"]["name"][$key];
//                    }
//                }
//                $count++;
//            }
//            echo "<script>";
//            echo "var b=confirm(\"总共${count}张图片。成功${success_count}张，失败${error_count}张!\");";
//            echo "if(b==true) location.href='/image';";
//            echo "</script>";
        }
    }

    public function actionUpload() {
        if (Yii::$app->request->post('uploadpic') == '上传') {
            $folder = '/wwwroot/data/image/shezhen/' . date('Ymd') . '/';
            $arr = [];
            $count = 0;
            $success_count = 0;
            $error_coun = 0;
            if (!file_exists($folder))
                mkdir($folder, 755);
            $tp = ["image/jpeg", "image/png"];
            foreach ($_FILES["uploads"]["error"] as $key => $error) {
                if (!in_array($_FILES["uploads"]["type"][$key], $tp))
                    exit("<script language='javascript'>alert(\"文件类型错误!\");</script>");
                if ($error == "UPLOAD_ERR_OK") {
                    $tmp_name = $_FILES["uploads"]["tmp_name"][$key];
                    $a = explode(".", $_FILES["uploads"]["name"][$key]);
                    $prename = $a[0];
                    $name = md5(time() . mt_rand(10000, 99999)) . '.' . $a[1];
                    $uploadfile = $folder . $name;     // 文件的路径
                    move_uploaded_file($tmp_name, $uploadfile);
                    $arr[$count] = $uploadfile;
                    $count++;
                }
            }
            echo "<script>";
            echo "var b=confirm(\"总共${count}张图片。成功${count}张，失败0张!\");";
            echo "if(b==true) location.href='/image';";
            echo "</script>";
        }
    }

    public function actionIndex() {
        if(Yii::$app->request->isAjax){
          $page = Yii::$app->request->get('page', 1);   
          $pageSize = 20; 
          $order = Yii::$app->request->get('order', 'uptime desc');
          $imageModel = new Image();
          $list = $imageModel->getImgList($page, $pageSize, $order);
          if(empty($list)){
              $this->_exit(-1);
          }
          $this->_exit(0, $list);
        }
        $imageModel = new Image();
        $page = Yii::$app->request->get('page', 1);
        $pageSize = 20;
        $order = Yii::$app->request->get('order', 'uptime desc');
        $list = $imageModel->getImgList($page, $pageSize, $order);
        echo $this->renderPartial('/image/index2', ['list' => $list]);
    }
    
    public function actionUploader(){
        echo $this->renderPartial('/image/uploader');
    }
    
    public function actionDemo(){
        echo $this->renderPartial('/image/demo2');
    }

    public function actionPackDown() {
        $imageUrls = Yii::$app->request->post('imageUrls');
        $image = [];
        $count = count($imageUrls);
        $count = $count > 100 ? 100 : $count;
        for ($i = 0; $i < $count; $i++) {
            $tmpImg = explode('/', $imageUrls[$i]);
            $imagName= $tmpImg[1];
            $image[$i]['image_src']= './uploads/'.$imageUrls[$i];
            $image[$i]['image_name']=$imagName;
        }
      
        //产生一个临时文件，用于缓存下载文件
        $dfile = tempnam('tmp/', 'tmp');
        $zip = new Zipfile();
        //----------------------
        $filename = 'image.zip'; //下载的默认文件名
        //以下是需要下载的图片数组信息，将需要下载的图片信息转化为类似即可

        foreach ($image as $v) {
            $zip->add_file(file_get_contents($v['image_src']), $v['image_name']);
            // 添加打包的图片，第一个参数是图片内容，第二个参数是压缩包里面的显示的名称, 可包含路径
            // 或是想打包整个目录 用 $zip->add_path($image_path);
        }
        //----------------------
        $zip->output($dfile);

        // 下载文件
        ob_clean();
        header('Pragma: public');
        header('Last-Modified:' . gmdate('D, d M Y H:i:s') . 'GMT');
        header('Cache-Control:no-store, no-cache, must-revalidate');
        header('Cache-Control:pre-check=0, post-check=0, max-age=0');
        header('Content-Transfer-Encoding:binary');
        header('Content-Encoding:none');
        header('Content-type:multipart/form-data');
        header('Content-Disposition:attachment; filename="' . $filename . '"'); //设置下载的默认文件名
        header('Content-length:' . filesize($dfile));
        $fp = fopen($dfile, 'r');
        while (connection_status() == 0 && $buf = @fread($fp, 8192)) {
            echo $buf;
        }
        fclose($fp);
        @unlink($dfile);
        @flush();
        @ob_flush();
        exit();
    }
    
    

}
